package top.swimmer.tokenizer.core;

import top.swimmer.tokenizer.dictionary.AbstractDictionary;
import top.swimmer.tokenizer.dictionary.DictionaryFactory;
import top.swimmer.tokenizer.entities.Word;

import java.util.Deque;
import java.util.List;
import java.util.Queue;

import static top.swimmer.tools.str.CharacterUtils.isUseless;
import static top.swimmer.tools.str.StringUtils.isEmpty;

/**
 * Created by xiaoyou on 16-12-11.
 */
public abstract class AbstractSegmentation implements Segmentation {
    abstract List<Word> segmentation(String text);

    AbstractDictionary getDictionary() {
        return DictionaryFactory.getDoubleArrayTrieDictionary();
    }

    void addWord(Deque<Word> words, String text, Integer start, Integer length) {
        Word word = buildWord(text, start, length);
        if (word != null) {
            words.push(word);
        }
    }

    void addWord(Queue<Word> words, String text, Integer start, Integer length) {
        Word word = buildWord(text, start, length);
        if (word != null) {
            words.offer(word);
        }
    }

    private Word buildWord(String text, Integer start, Integer length) {
        String wordStr = text.substring(start, start + length);
        if (isUselessWord(wordStr)) {
            return null;
        }
        Word word = new Word();
        word.setContent(wordStr);
        return word;
    }

    private boolean isUselessWord(String text) {
        return isEmpty(text) || (text.length() == 1 && isUseless(text.charAt(0)));
    }
}
